package com.YCH.article.service.impl;

import com.YCH.article.service.AppArticleInfoService;
import com.YCH.model.address.pojos.TbAreas;
import com.YCH.model.article.dtos.ArticleActionAndConfigDto;
import com.YCH.model.article.dtos.ArticleActionDto;
import com.YCH.model.article.dtos.ArticleInfoDto;
import com.YCH.model.article.pojos.*;
import com.YCH.model.article.vos.*;
import com.YCH.model.behavior.dtos.userCommentReplayDto;
import com.YCH.model.behavior.pojos.*;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.mappers.app.*;
import com.YCH.model.user.pojos.TbUser;
import com.YCH.model.user.pojos.TbUserFollow;
import com.YCH.utils.common.ZipUtils;
import com.YCH.utils.threadlocal.AppThreadLocalUtils;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.Level;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.*;

@Getter
@Service
@Log4j2
@SuppressWarnings("all")
public class AppArticleInfoServiceImpl implements AppArticleInfoService {
    @Autowired
    private TbArticleConfigMapper tbArticleConfigMapper;
    @Autowired
    private TbCollectionBehaviorMapper tbCollectionBehaviorMapper;
    @Autowired
    private TbLikesBehaviorMapper tbLikesBehaviorMapper;
    @Autowired
    private TbUnlikesBehaviorMapper tbUnlikesBehaviorMapper;
    @Autowired
    private TbAuthorMapper tbAuthorMapper;
    @Autowired
    private TbUserFollowMapper tbUserFollowMapper;
    @Autowired
    private TbArticleCommentMapper tbArticleCommentMapper;
    @Autowired
    private TbArticleCommentReplayMapper tbArticleCommentReplayMapper;
    @Autowired
    private TbShowBehaviorMapper tbShowBehaviorMapper;
    @Autowired
    private TbArticleMapper tbArticleMapper;
    @Autowired
    private TbArticleContentMapper tbArticleContentMapper;
    @Autowired
    private TbForwardBehaviorMapper tbForwardBehaviorMapper;
    @Autowired
    private TbAreasMapper tbAreasMapper;
    @Autowired
    private TbUserMapper tbUserMapper;
    /**
     * 加载文章配置、详细性息
     *
     * @param articleId
     * @return
     */
    @Override
    public ResponseResult getArticleInfo(Long articleId) {
        // 参数无效
        if (articleId == null || articleId < 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        TbArticleConfig config = tbArticleConfigMapper.selectByArticleId(articleId);
        Map<String, Object> data = new HashMap<>();
        // 参数无效
        if (config == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        } else if (!config.getIsDelete()) {
            // 没删除的标识才返回给客户端
            // 查询
            TbArticle tbArticle = tbArticleMapper.loadArticleContentInfo(articleId);
            // 查看该文章是否为public，是则继续否则返回
            Boolean isPublic = tbArticleConfigMapper.selectByArticleId(tbArticle.getId()).getIsPublic();
            if(!isPublic){
                return ResponseResult.okResult(200,"该文章暂未被开放！");
            }
            // 返回vo
            ApArticleContentInfo apArticleContentInfo = new ApArticleContentInfo();
            apArticleContentInfo.setId(tbArticle.getId());
            apArticleContentInfo.setTagName(tbArticle.getFlag().getTagName());
            apArticleContentInfo.setTitle(tbArticle.getTitle());
            String content = ZipUtils.gunzip(tbArticle.getContent().getContent());
            apArticleContentInfo.setContent(content);
            apArticleContentInfo.setCreatTime(tbArticle.getCreatTime());
            try {
                apArticleContentInfo.setTagId(tbArticle.getFlag().getId());
                apArticleContentInfo.setCategoryId(tbArticle.getCategoryId());
                apArticleContentInfo.setProvinceId(tbArticle.getProvinceId());
                apArticleContentInfo.setCityId(tbArticle.getCityId());
                apArticleContentInfo.setCountyId(tbArticle.getCountyId());
            } catch (NullPointerException e) {
                e.printStackTrace();
                log.log(Level.ERROR,"参数为空"+e);
            }
            data.put("apArticleContentInfo", apArticleContentInfo);
        }
        data.put("config", config);
        return ResponseResult.okResult(data);
    }

    /**
     * 加载文章行为信息，比如关注、点赞(喜欢)、不喜欢、收藏、转发、阅读位置、等
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if(dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        boolean isLike = false, isCollection = false, isFollow = false, isUnLike = false, isforward = false;
        TbUser user = AppThreadLocalUtils.getUser();
        // 没登陆就全部返回false
        if (user != null || dto.getUserId() != null) {
            Long userId = null;
            if (user != null) {
                userId = user.getId();
            }else if(dto.getUserId()!=null){
                userId = dto.getUserId();
            }
            // 判断是否关注
            TbAuthor tbAuthor = tbAuthorMapper.selectById(dto.getAuthorId());
            if (user != null && tbAuthor != null && tbAuthor.getUserId() != null) {
                TbUserFollow apUserFollow = tbUserFollowMapper.selectByFollowId(user.getId(), tbAuthor.getUserId());
                if (apUserFollow != null) {
                    isFollow = true;
                }
            }
            // 判断是否是已经点赞(喜欢)
            TbLikesBehavior tbLikesBehavior = tbLikesBehaviorMapper.selectLastLike(userId, dto.getArticleId(),null,null, TbCollectionBehavior.CollectionContentType.ARTICLE.getCode());
            // 当数据不为空，且没有取消点赞（operation === 0）
            if (tbLikesBehavior != null && tbLikesBehavior.getOperation() == TbLikesBehavior.Operation.LIKE.getCode()) {
                isLike = true;
            }
            // 判断是否是已经不喜欢
            TbUnlikesBehavior tbUnlikesBehavior = tbUnlikesBehaviorMapper.selectLastUnLike(userId, dto.getArticleId());
            if (tbUnlikesBehavior != null && tbUnlikesBehavior.getType() == TbUnlikesBehavior.Type.UNLIKE.getCode()) {
                isUnLike = true;
            }
            // 判断是否收藏
            TbCollectionBehavior tbCollectionBehavior = tbCollectionBehaviorMapper.selectForUserId(userId, dto.getArticleId(), TbCollectionBehavior.CollectionContentType.ARTICLE.getCode());
            if (tbCollectionBehavior != null && tbCollectionBehavior.getOperation() == TbCollectionBehavior.Operation.COLLECTED.getCode()) {
                isCollection = true;
            }
            // 判断是否转发
            TbForwardBehavior tbForwardBehavior = tbForwardBehaviorMapper.selectForwardByUserIdAndarticleId(userId, dto.getArticleId());
            if (tbForwardBehavior != null) {
                isFollow = true;
            }
        }
        // 获取阅读位置
        Map<String, Boolean> relation = Maps.newHashMap();
        relation.put("isFollow", isFollow);
        relation.put("isLike", isLike);
        relation.put("isUnlike", isUnLike);
        relation.put("isCollection", isCollection);
        relation.put("isForward", isforward);
        return ResponseResult.okResult(relation);
    }

    /**
     * 加载文章观看、点赞、收藏、评论数量
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleAction(ArticleActionDto dto) {
        if (dto.getArticleId() == null || dto.getArticleId() <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getType() > 1 || dto.getType() < 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 查看人数
        Integer viewCount = tbShowBehaviorMapper.selectViewCount(dto.getArticleId(), ArticleActionDto.Type.CLICKED.getCode());
        // 点赞人数
        Integer fabulousCount = tbLikesBehaviorMapper.selectAllCount(dto.getArticleId(),null,null, dto.getType());
        // 收藏人数
        Integer collectionCount = tbCollectionBehaviorMapper.selectCollectionCount(dto.getArticleId(), dto.getType());
        // 评论人数
        Integer commentCount = tbArticleCommentMapper.selectCommentCount(dto.getArticleId());
        Integer commentReplayCount = tbArticleCommentReplayMapper.selectCommentReplayCount(dto.getArticleId());
        ArticleActionVo articleActionVo = new ArticleActionVo();
        articleActionVo.setCollectionCount(collectionCount);
        articleActionVo.setViewCount(viewCount);
        articleActionVo.setFabulousCount(fabulousCount);
        try {
            articleActionVo.setCommentCount(commentCount + commentReplayCount);
        } catch (NullPointerException e) {
            log.log(Level.ERROR,"评论值为空！" + e.getStackTrace());
            articleActionVo.setCommentCount(0);
            return ResponseResult.okResult(articleActionVo);
        }
        return ResponseResult.okResult(articleActionVo);
    }

    /**
     * 加载 观看、点赞、收藏、评论数量 …… 及其配置
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleActionAndConfig(ArticleActionAndConfigDto dto) {
        // 不需要校验参数，下面的方法调用本类的方法，被调用的方法会校验参数
        if(dto.getArticleId()==null || dto.getArticleId() <=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getType()<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 数量
        ArticleActionDto articleActionDto = new ArticleActionDto();
        articleActionDto.setArticleId(dto.getArticleId());
        articleActionDto.setType(dto.getType());
        ArticleActionVo data1 = (ArticleActionVo) loadArticleAction(articleActionDto).getData();
        // 是否……
        ArticleInfoDto articleInfoDto = new ArticleInfoDto();
        articleInfoDto.setArticleId(dto.getArticleId());
        articleInfoDto.setAuthorId(dto.getAuthorId());
        articleInfoDto.setUserId(dto.getUserId());
        Map<String, Boolean> data = (Map<String, Boolean>) loadArticleBehavior(articleInfoDto).getData();

        ArticleActionAndConfigVo articleActionAndConfigVo = new ArticleActionAndConfigVo();
        articleActionAndConfigVo.setCommentCount(data1.getCommentCount());
        articleActionAndConfigVo.setCollectionCount(data1.getCollectionCount());
        articleActionAndConfigVo.setViewCount(data1.getViewCount());
        articleActionAndConfigVo.setFabulousCount(data1.getFabulousCount());

        articleActionAndConfigVo.setIsCollection(data.get("isCollection"));
        articleActionAndConfigVo.setIsFollow(data.get("isFollow"));
        articleActionAndConfigVo.setIsforward(data.get("isForward"));
        articleActionAndConfigVo.setIsLike(data.get("isLike"));
        articleActionAndConfigVo.setIsUnLike(data.get("isUnlike"));
        articleActionAndConfigVo.setArticleId(dto.getArticleId());
        articleActionAndConfigVo.setReadPosition(null);
        return ResponseResult.okResult(articleActionAndConfigVo);
    }

    /**
     * 加载当前文章的评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleCommenty(ArticleInfoDto dto) {
        // 1.校验参数
        if(dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"文章id不能为空");
        }
        // 2.获取评论内容
        List<TbArticleComment> tbArticleComments = tbArticleCommentMapper.selectArticleCommentByArticleId(dto.getArticleId().longValue());
        // 3创建tbArticleCommentsVo；
        List<TbArticleCommentSVO> tbArticleCommentSVOs = new ArrayList<>();
        // 3.1封装结果tbArticleCommentsVo
        for (TbArticleComment tbArticleComment:tbArticleComments) {
            // 3.2 评论内容、评论内容转码
            tbArticleComment.setContent(ZipUtils.gunzip(tbArticleComment.getContent()));
            TbArticleCommentSVO tbArticleCommentSVO = new TbArticleCommentSVO();
            tbArticleCommentSVO.setTbArticleCommen(tbArticleComment);
            // 3.3 评论作者信息 根据TbArticleComment_insert.userId获取用户信息（用户名、签名、头像、等级）
            TbUser tbUser = tbUserMapper.selectLvByIdSimple(tbArticleComment.getUserId());
            tbArticleCommentSVO.setUser(tbUser);
            // 3.4 评论点赞数量 （查询tb_likesBehavior type==2)
            Integer count = tbLikesBehaviorMapper.selectAllCount(null,tbArticleComment.getId(),null, (short) 2);
            tbArticleCommentSVO.setFabulousCount(count);
            tbArticleCommentSVOs.add(tbArticleCommentSVO);
            // 3.5 评论是否已近点赞
            TbLikesBehavior tbLikesBehavior = tbLikesBehaviorMapper.selectLastLike(tbArticleComment.getUserId(), null, tbArticleComment.getId(), null, (short) 1);
            // 3.6 当数据不为空，且没有取消点赞（operation === 0）
            if (tbLikesBehavior != null && tbLikesBehavior.getOperation() == TbLikesBehavior.Operation.LIKE.getCode()) {
                tbArticleCommentSVO.setIsLike(true);
            }else {
                tbArticleCommentSVO.setIsLike(false);
            }
            // 3.7 查看当前评论的最新两条回复
            userCommentReplayDto dto1 = new userCommentReplayDto();
            dto1.setArticleId(tbArticleComment.getArticle().getId());
            dto1.setCommentId(tbArticleComment.getId());
            dto1.setPageSize(2);
            ResponseResult responseResult = loadCommentReplay(dto1);
            tbArticleCommentSVO.setApCommentReplayVos((List<ApCommentReplayVo>) responseResult.getData());
        }
        return ResponseResult.okResult(tbArticleCommentSVOs);
    }

    /**
     * 获取用户发布的云记
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult ObtainUserPrivateCloudNoteN() {
        // 获取用户信息
        TbUser user = AppThreadLocalUtils.getUser();
        // 判断用户是否存在
        if (user == null) {
            return ResponseResult.errorResult(200, "用户未登录");
        }
        Long id = user.getId();
        List<TbArticle> tbArticles = tbArticleMapper.loadArticleListByUserId(id);
        // 封装到vo列表,用于显示我发表的云记
        List<ApShowArticle> tbShowArticleList = new ArrayList<>();
        // 循环 拿到的用户的文章
        for (TbArticle tbArticle : tbArticles) {
            ApShowArticle apShowArticle = new ApShowArticle();
            // 获取ArticleActionDtos，以查询点赞、查看、收藏、评论数量
            ArticleActionDto articleActionDto = new ArticleActionDto();
            articleActionDto.setArticleId(tbArticle.getId());
            // 因为是获取我的文章，故而type固定为0
            articleActionDto.setType(ArticleActionDto.Type.CLICKED.getCode());
            ArticleShowList articleShowList = new ArticleShowList();
            articleShowList.setArticleId(tbArticle.getId());
            articleShowList.setPartContent(tbArticle.getPartContent());
            articleShowList.setTitle(tbArticle.getTitle());
            articleShowList.setCustomTag(tbArticle.getTag());
            // 设置文章内容
            apShowArticle.setContent(articleShowList);
            // 设置时间
            apShowArticle.setCreatTime(tbArticle.getCreatTime());
            ArticleActionVo articleActionVo = (ArticleActionVo) loadArticleAction(articleActionDto).getData();
            apShowArticle.setArticleOpeartor(articleActionVo);
            // 封装到vo列表
            tbShowArticleList.add(apShowArticle);
        }
        if (tbShowArticleList.isEmpty()) {
            return ResponseResult.okResult(200, "您还没有写云记哦！");
        }
        return ResponseResult.okResult(tbShowArticleList);
    }

    /**
     * 获取地址
     * @param tbAreas
     * @return
     */
    @Override
    public ResponseResult loadLocation(TbAreas tbAreas) {
        // 1.校验参数
        if(tbAreas.getParentId()<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<TbAreas> tbAreases = tbAreasMapper.loadAddressByParentId(tbAreas.getParentId());
        return ResponseResult.okResult(tbAreases);
    }

    /**
     * 查询更多回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentReplay(userCommentReplayDto dto) {
        // 1.校验参数
        if(dto.getArticleId() == null || dto.getArticleId() <=0 ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getCommentId() == null || dto.getCommentId() <=0 ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getCommentReplayId() == null ){
            // 如果为空，什么都不做
        }else if (dto.getCommentReplayId() <= 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 默认每页为10个
        if (dto.getPageSize() == null || dto.getPageSize() <= 0){
            dto.setPageSize(10);
        }
        // 默认第一页
        if(dto.getPageNum() == null || dto.getPageNum() <= 0){
            dto.setPageNum(1);
        }
        PageHelper.clearPage();
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        List<TbArticleCommentReplay> tbArticleCommentReplays = tbArticleCommentReplayMapper.selectCommentsByarticleIdAndcommentId(dto);
        PageInfo<TbArticleCommentReplay> pageInfo = new PageInfo<>(tbArticleCommentReplays);
        List<TbArticleCommentReplay> list = pageInfo.getList();
        if (list.isEmpty() || list.size() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<ApCommentReplayVo> apCommentReplayVos = new ArrayList<>();
        for (TbArticleCommentReplay tbArticleCommentReplay:list) {
            ApCommentReplayVo apCommentReplayVo = new ApCommentReplayVo();
            // 1.查询用户信息
            tbArticleCommentReplay.setUser(tbUserMapper.selectLvByIdSimple(tbArticleCommentReplay.getUser().getId()));
            // 1.1解密回复内容
            tbArticleCommentReplay.setContent(ZipUtils.gunzip(tbArticleCommentReplay.getContent()));
            apCommentReplayVo.setTbArticleCommentReplay(tbArticleCommentReplay);
            // 2.查询点赞人数
            Integer integer = tbArticleCommentReplayMapper.selectCommentReplayCountById(tbArticleCommentReplay.getId());
            apCommentReplayVo.setCount(integer);
            // 3.查询是否点赞
            TbLikesBehavior tbLikesBehavior = new TbLikesBehavior();
            if(tbArticleCommentReplay.getCommentReplayId()==0){
                tbLikesBehavior = tbLikesBehaviorMapper.selectLastLike(tbArticleCommentReplay.getUser().getId(), null, null, tbArticleCommentReplay.getId(), (short) 1);
            }else {
                tbLikesBehavior = tbLikesBehaviorMapper.selectLastLike(tbArticleCommentReplay.getUser().getId(), null, null, tbArticleCommentReplay.getCommentReplayId(), (short) 1);
            }
            // 3.1当数据不为空，且没有取消点赞（operation === 0）
            if (tbLikesBehavior != null && tbLikesBehavior.getOperation() == TbLikesBehavior.Operation.LIKE.getCode()) {
                apCommentReplayVo.setIsLike(true);
            }else {
                apCommentReplayVo.setIsLike(false);
            }
            apCommentReplayVos.add(apCommentReplayVo);
        }
        // pageInfo.setList(list);
        return ResponseResult.okResult(apCommentReplayVos);
    }
}